package com.promis.widget.paging;

import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

public class OnPageScrollListener extends RecyclerView.OnScrollListener {

    private int lastVisibleItem;
    private int fristVisibleItem;

    private boolean hasMore = true;

    private SwipeRefreshLayout swipeRefreshLayout;

    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);

        //判断RecyclerView的状态 是空闲时，同时，是最后一个可见的ITEM时才加载
        if(newState== RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == recyclerView.getAdapter().getItemCount()){
            if (hasMore) onLoadPageData();
            onPullUp();
//        } else if(newState== RecyclerView.SCROLL_STATE_IDLE && fristVisibleItem == 0){
//            onRefresh();
//            onPullDown();
        }

        int topRowVerticalPosition = (recyclerView == null || recyclerView.getChildCount() == 0) ? 0 : recyclerView.getChildAt(0).getTop();
        if (swipeRefreshLayout != null) swipeRefreshLayout.setEnabled(topRowVerticalPosition >= 0);
    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);

        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        //最后一个可见的ITEM
        lastVisibleItem=layoutManager.findLastVisibleItemPosition();
        fristVisibleItem = layoutManager.findFirstVisibleItemPosition();
    }

    public void setSwipeRefreshLayout(SwipeRefreshLayout swipeRefreshLayout) {
        this.swipeRefreshLayout = swipeRefreshLayout;
    }

    public void onRefreshComplete(final boolean hasMore) {
        this.hasMore = hasMore;
    }

    public void onLoadPageData() {}

    public void onPullUp() {}

//    public void onRefresh() {}
//
//    public void onPullDown() {}
}
